package com.xhwl.centiotdata.suppliersystem.huawei;

import com.alibaba.fastjson.JSONObject;
import com.huaweicloud.sdk.core.exception.ClientRequestException;
import com.xhwl.centiotdata.pojo.constant.HuaWeiIoTDAConstant;
import com.xhwl.centiotdata.pojo.dto.huawei.IOTConfigDTO;
import com.xhwl.common.dto.cent.security.PerimeterActionDTO;
import com.xhwl.common.pojo.cent.security.PatrollingLine;
import com.xhwl.common.pojo.cent.security.PatrollingPlan;
import com.xhwl.common.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Author: yanyixiong
 * @Description:
 * @Date: create in 10:53 2022/1/17
 */
@Slf4j
@Service
public class SecurityHuaWeiIoTDAHandler {

    @Autowired
    private GeneralHuaWeiIoTDAHandler generalHuaWeiIoTDAHandler;

    public boolean perimeterAction(IOTConfigDTO configDTO, PerimeterActionDTO perimeterActionDTO) {
        boolean isSuccess = true;
        Map<String, Integer> params = new HashMap<>(1);
        try {
            //Instruct命令（1：设防，2：旁路，3：撤防）
            params.put("value", perimeterActionDTO.getAction().getType());
            JSONObject resultObject = generalHuaWeiIoTDAHandler.command(configDTO.getAk(), configDTO.getSk(), configDTO.getRegion(), perimeterActionDTO.getIotDeviceId(), HuaWeiIoTDAConstant.PERIMETER_SERVICE_ID, "Instruct", params);
            if (resultObject.getInteger("result_code") != 1 && resultObject.getInteger("result_code") != 0) {
                isSuccess = false;
            }
        } catch (ClientRequestException e) {
            log.error("电子围栏命令执行异常：{}", e.getErrorMsg());
            isSuccess = false;
        }
        return isSuccess;
    }

    public JSONObject onPushingPatrolsLine(IOTConfigDTO configDTO, PatrollingLine line, String oldName, List<String> nodeIds, String command) {
        try {
            String[] commander = command.split(",");

            JSONObject extras = new JSONObject();
            extras.put("sectorID", Integer.parseInt(configDTO.getSectorId()));
            extras.put("lineName", line.getName());
            extras.put("oldLineName", oldName);
            extras.put("newLineName", line.getName());
            extras.put("placeIDList", StringUtils.arrToStr(nodeIds, "|"));

            JSONObject params = new JSONObject();
            params.put(commander[1], extras);

            return generalHuaWeiIoTDAHandler.command(
                    configDTO.getAk(), configDTO.getSk(), configDTO.getRegion(), configDTO.getPatrolineDI(), commander[0], commander[1], params
            );
        } catch (ClientRequestException e) {
            log.error("电子围栏命令执行异常：{}", e.getErrorMsg());
        }
        return new JSONObject();
    }

    public JSONObject onPushingPatrolsPlan(IOTConfigDTO configDTO, PatrollingPlan plan, String command) {
        try {
            String[] commander = command.split(",");

            SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd");
            SimpleDateFormat timeformat = new SimpleDateFormat("HH:mm:ss");

            JSONObject extras = new JSONObject();
            extras.put("planMode", Optional.ofNullable(plan.getFixedOrder()).orElse(0));
            extras.put("planType", 0);

            Date startDate = Optional.ofNullable(plan.getStartDate()).orElse(new Date());
            extras.put("planStartTime", timeformat.format(startDate));
            extras.put("planStartExecuteDate", dateformat.format(startDate));

            if (plan.getEndDate() != null) {
                extras.put("planEndTime", timeformat.format(plan.getEndDate()));
                extras.put("planEndExecuteDate", dateformat.format(plan.getEndDate()));
            } else {
                Calendar calendar = Calendar.getInstance();
                calendar.add(Calendar.HOUR_OF_DAY, 1);
                extras.put("planEndTime", timeformat.format(calendar.getTime()));
                extras.put("planEndExecuteDate", "");
            }
            extras.put("planExecuteFlag", true);

            extras.put("lineName", plan.getLineName());
            extras.put("planMinTimeLap", 10);
            extras.put("placeTimeError", 0);
            extras.put("bindingUserID", 0);
            extras.put("bindingUserFlag", 0);
            extras.put("bindingReaderID", 0);
            extras.put("bindingReaderFlag", 0);

            extras.put("bindingWeekday", "");
            extras.put("planStartDay", 0);
            extras.put("planEndDay", 0);
            extras.put("patrolDuration", 0);
            extras.put("patrolCount", 0);
            extras.put("timeInterval", 0);

            extras.put("aheadOfHintTime", 0);
            extras.put("patrolDurationType", 0);
            extras.put("patrolDurationInterval", 0);

            extras.put("placeIDListString", "");
            extras.put("bindingUserIDList", "");
            extras.put("bindingReaderIDList", "");
            extras.put("placeTimeListString", "");

            extras.put("sectorID", Integer.parseInt(configDTO.getSectorId()));
            if (plan.getPlatformId() != null) {
                extras.put("planID", Integer.parseInt(plan.getPlatformId()));
            }

            JSONObject params = new JSONObject();
            params.put(commander[1], extras);

            return generalHuaWeiIoTDAHandler.command(
                    configDTO.getAk(), configDTO.getSk(), configDTO.getRegion(), configDTO.getPatroplanDI(), commander[0], commander[1], params
            );
        } catch (ClientRequestException e) {
            log.error("电子围栏命令执行异常：{}", e.getErrorMsg());
        }
        return new JSONObject();
    }

    public JSONObject onGettingCheckRecord(IOTConfigDTO configDTO, JSONObject jsparams, String command) {
        try {
            String[] commander = command.split(",");

            JSONObject extras = new JSONObject();
            extras.put("startTime", jsparams.getString("startTime"));
            extras.put("endTime", jsparams.getString("endTime"));
            extras.put("sectorID", Integer.parseInt(configDTO.getSectorId()));
            extras.put("patrolUser", "");
            extras.put("placeName", "");
            extras.put("patrolReader", "");
            extras.put("viewErrorDataOnlyFlag", "");
            extras.put("pageNo", 1);
            extras.put("rowCount", 1000);

            JSONObject params = new JSONObject();
            params.put(commander[1], extras);

            return generalHuaWeiIoTDAHandler.command(
                    configDTO.getAk(), configDTO.getSk(), configDTO.getRegion(), configDTO.getPatroplanDI(), commander[0], commander[1], params
            );
        } catch (ClientRequestException e) {
            log.error("电子围栏命令执行异常：{}", e.getErrorMsg());
        }
        return new JSONObject();
    }

}
